package cn.zyg.ymcc.service.impl;

import cn.zyg.ymcc.constants.RedisSmsConstants;
import cn.zyg.ymcc.domain.Login;
import cn.zyg.ymcc.domain.User;
import cn.zyg.ymcc.domain.UserAccount;
import cn.zyg.ymcc.domain.UserBaseInfo;
import cn.zyg.ymcc.dto.PhoneRegisterDto;
import cn.zyg.ymcc.dto.RedisSmsDto;
import cn.zyg.ymcc.enums.GlobalExceptionCode;
import cn.zyg.ymcc.feign.LoginService;
import cn.zyg.ymcc.mapper.UserMapper;
import cn.zyg.ymcc.result.JSONResult;
import cn.zyg.ymcc.service.IUserAccountService;
import cn.zyg.ymcc.service.IUserBaseInfoService;
import cn.zyg.ymcc.service.IUserService;
import cn.zyg.ymcc.util.AssertUtil;
import cn.zyg.ymcc.util.BitStatesUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author zyg
 * @since 2022-09-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private LoginService loginService;
    @Autowired
    private IUserBaseInfoService userBaseInfoService;
    @Autowired
    private IUserAccountService userAccountService;

    @Override
    @Transactional
    public void register(PhoneRegisterDto phoneRegisterDto) {
        String mobile = phoneRegisterDto.getMobile();
        String password = phoneRegisterDto.getPassword();
        String smsCode = phoneRegisterDto.getSmsCode();
        Integer regChannel = phoneRegisterDto.getRegChannel();
        // 1.参数校验JSR303
        // 2.拼接业务键，去redis中获取短信验证码进行校验
        String redisKey = String.format(RedisSmsConstants.REDIS_REGISTER_PHONE_KEY, mobile);
        Object obj = redisTemplate.opsForValue().get(redisKey);
        //  2.1 如果短信验证码为空，抛异常
        AssertUtil.isNotNull(obj, GlobalExceptionCode.CODE_IS_NULL_ERROR);
        //  2.2 判断验证码是否正确
        RedisSmsDto redisSmsDto = (RedisSmsDto)obj;
        AssertUtil.isEquals(smsCode,redisSmsDto.getCode(),GlobalExceptionCode.CODE_ERROR);
        // 3.根据手机号查询用户信息
        User user = selectUser(mobile);
        AssertUtil.isNotNull(user,GlobalExceptionCode.USER_EXISTED_ERROR);
        // 4.保存login
        JSONResult jsonResult = savaLogin(phoneRegisterDto);
        // 4.1 断言是否成功
        AssertUtil.isTrue(jsonResult.isSuccess(),GlobalExceptionCode.USER_SAVE_ERROR);
        // 4.2 断言ID是否为null
        AssertUtil.isNotNull(jsonResult.getData(),GlobalExceptionCode.ERROR);
        Long loginId = Long.valueOf(jsonResult.getData().toString());
        // 5. 保存user相关表
        //  5.1 保存用户信息
        Long userId = saveUser(loginId, phoneRegisterDto);
        //  5.2 保存用户基本信息
        initUserBaseInfo(userId,regChannel);
        //  5.3 保存用户账号信息
        initUserAccount(userId);

    }

    private void initUserAccount(Long userId) {
        UserAccount userAccount = new UserAccount();
        userAccount.setCreateTime(new Date().getTime());
        userAccount.setPassword("123456");
        userAccount.setId(userId);
        userAccount.setFrozenAmount(new BigDecimal(0));
        userAccount.setUsableAmount(new BigDecimal(0));
        userAccountService.insert(userAccount);
    }

    private void initUserBaseInfo(Long userId,Integer regChannel) {
        UserBaseInfo userBaseInfo = new UserBaseInfo();
        userBaseInfo.setId(userId);
        userBaseInfo.setRegChannel(regChannel);
        userBaseInfo.setCreateTime(new Date().getTime());
        userBaseInfoService.insert(userBaseInfo);
    }

    private Long saveUser(Long loginId, PhoneRegisterDto phoneRegisterDto) {
        User user = new User();
        user.setCreateTime(new Date().getTime());
        user.setLoginId(loginId);
        user.setNickName(phoneRegisterDto.getMobile());
        user.setPhone(phoneRegisterDto.getMobile());
        // 得到用户初始化位状态
        long state = BitStatesUtils.addState(BitStatesUtils.OP_REGISTED, BitStatesUtils.OP_ACTIVED);
        state = BitStatesUtils.addState(state,BitStatesUtils.OP_AUTHED_PHONE);
        // 设置用户初始状态值
        user.setBitState(state);
        insert(user);
        return user.getId();
    }

    private JSONResult savaLogin(PhoneRegisterDto phoneRegisterDto) {
        Login login = new Login();
        login.setUsername(phoneRegisterDto.getMobile());
        login.setPassword(phoneRegisterDto.getPassword());
        login.setType(Login.USER_TYPE);
        login.setEnabled(Login.ENABLE);
        return loginService.saveOrUpdate(login);
    }

    // 根据电话号码查询用户信息
    private User selectUser(String mobile) {
        // 1.创建user对象的条件构造器
        Wrapper<User> wrapper = new EntityWrapper<>();
        // 2.设置查询条件
        wrapper.eq("phone",mobile);

        return selectOne(wrapper);
    }
}
